<?php
/**
 * @author Feng
 * @date 2012-6-5
 */
class controller_admin_picture_swfupload extends system_user_controller_ajax {
	
	private $concept = null;
	public function init() {
		$this->_resetSession();
		if(!parent::init()) {
			return ;
		}
		$this->concept = new picture_photo_localeConcept($this->user->getLang());
	}
		
	public function action_index() {
		$typeConcept = $this->_checkType();
		$action = '_upload_' . strtolower($typeConcept->getKey());
		$this->$action();
	}
	
	public function action_ajaxedit() {
		if(!$this->getRequest()->isPost()) {
			$this->_error('Invalid Params');
		}
		$special_id = intval($this->_post('special_id'));
		$id = intval($this->_post('id'));

		if(!($row = $this->concept->fetch(array('photo.id = ?' => $id)))) {
			$this->_error("The Photo is not Existing.");
		}
		if($this->_post('swfupload')) {
			$typeConcept = $this->_checkType();
			try {
				system_db::getAdapter()->beginTransaction();
				resource_api_image::setWatermark((array) resource_config_image::getWatermark());
				$res = resource_api_image::create($_FILES['file']);
				if($row->getHash() == $res->getHash()) {
					$this->_error("The Photo you uploaded is NOT Changed.");
				}
				$checkExisting = true;
				if($special_id > 0) {
					$checkExisting = false;
				}
				if($special_id > 0 && $this->concept->fetch(array('photo.id != ?' => $id, 'photo.id IN(SELECT `photo_id` FROM `picture_special_photo` WHERE `special_id` = ?)' => $special_id, 'photo.hash = ?' => $res->getHash()))) {
					$this->_error("This Photo is already in the Special.");
				}
				$file = $_FILES['file'];
				$res->save();
				$row->setHash($res->getHash());
				$row->save($checkExisting);
				system_db::getAdapter()->commit();
				$file['hash'] = $res->getHash();
				$this->_data->file = $file;
				$this->_output();
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->_error($e->getMessage());
			}
		}
		if($this->_post('submit')) {
			$this->saveRow($row);
		}
		if($this->_post('saveShow')) {
			$this->saveRow($this->concept->fetch(array('photo.id = ?' => intval($this->_post('save_id')))), false);
		}
		if($this->_post('setCover')) {
			try {
				system_db::getAdapter()->beginTransaction();
				$concept = new picture_special_localeConcept();
				if(!($special = $concept->fetch(array('special.id = ?' => $special_id)))) {
					throw new picture_exception("Special is not Existing.");
				}
				$special->setCover($row->getHash());
				$special->update();
				system_db::getAdapter()->commit();
				$this->_output('Complete');
			} catch (Exception $e) {
				system_db::getAdapter()->rollBack();
				$this->_error($e->getMessage());
			}
		}
		$where = array();
		if($special_id > 0) {
			$_npConcept = $this->concept;
			$where = array('photo.id IN(SELECT `photo_id` FROM `picture_special_photo` WHERE `special_id` = ?)' => $special_id);
		} else {
			$_npConcept = new picture_photo_concept($this->user->getLang());
		}
		$_next = $_previous = null;
		if(1 && $next = $_npConcept->fetch(array_merge(array('photo.id > ?' => $row->getId()), $where), array('id ASC', 'creationtime DESC'))) {
			$_next = $next->getId();
		}
		if(1 && $previous = $_npConcept->fetch(array_merge(array('photo.id < ?' => $row->getId()), $where), array('id DESC', 'creationtime ASC'))) {
			$_previous = $previous->getId();
		}
		if($special_id > 0) {
			$this->_data->next = $_next;
			$this->_data->previous = $_previous;
		} else {
			$this->_data->next = $_previous;
			$this->_data->previous = $_next;
		}
		$this->_data->hash = $row->getHash();
		$this->_data->formHtml = $this->view->partial('picture/photo/ajaxRow.phtml', array('row' => $row, 'post' => $this->_post()));
		$this->_output();
	}
	
	private function saveRow($row, $output = true) {
		if(!$row) return false;
		try {
			system_db::getAdapter()->beginTransaction();
			$row->getLocale()->setTitle(trim($this->_post('title')));
			$row->getLocale()->setDescription($this->_post('description'));
			$row->setDisplayOrder(intval($this->_post('display_order')));
			$row->setIsActive(intval($this->_post('is_active')) ? 1 : 0);
			$row->setKeywords(trim($this->_post('tag')));
			$row = $row->save(false);
			system_db::getAdapter()->commit();
			if($output) {
				$this->_output('Complete');
			}
		} catch (Exception $e) {
			system_db::getAdapter()->rollBack();
			if($output) {
				$this->_error($e->getMessage());
			}
		}
	}
	
	private function _upload_image() {
		try {
			system_db::getAdapter()->beginTransaction();	
			$sConcept = new picture_special_photo_concept();
			$spConcept = new picture_special_concept($this->user->getLang());		
			$special_id = (array) $this->_post('special_id');
			$setting = $this->_post('setting');			
			$insert_new = isset($setting['insert_new']) ? intval($setting['insert_new']) : 0;
			$return_info = isset($setting['return_information']) ? intval($setting['return_information']) : 0;
			$cutting_title = isset($setting['cutting_title']) ? intval($setting['cutting_title']) : 0;
			$allow_d_standard = isset($setting['allow_d_standard']) ? true : false;
			
			resource_api_image::setWatermark((array) $this->_post('watermark'));
			$res = resource_api_image::create($_FILES['file'], $allow_d_standard);
			$file = $_FILES['file'];
			$title = trim($file['name']);
			$limitExtensions = implode('|', resource_config_image::getExtensions());
			if($cutting_title && preg_match('/^(.*)\.(' . $limitExtensions . ')/is', $title, $match)) {
				$title = $match[1];
				$file['name'] = $title;
			}

			if(!($return_info && $row = $this->concept->fetch(array('photo.hash = ?' => $res->getHash())))) {
				$row = $this->concept->create();
				$row->setHash($res->getHash());
				$row->setDisplayOrder(0);
				$row->setIsActive(1);
				$row->getLocale()->setTitle($title);
				$row->getLocale()->setDescription('');
				$row = $row->save(!$insert_new);
			}
	
			$spRow = array();
			foreach($special_id AS $sid) {
				if(1 && $spRow[$sid] = $spConcept->fetch(array('special_id = ?' => $sid))) {
					$sRow = $sConcept->create();
					$sRow->setPhotoId($row->getId());
					$sRow->setSpecialId($sid);
					$sRow->save();
				}
			}
			
			foreach($spRow AS $_spRow) {
				$_spRow->updatePhotoCount();
			}
			
			$res->save();
			system_db::getAdapter()->commit();
			$file['hash'] = $row->getHash();
			$file['id'] = $row->getId();
			$this->_data->file = $file;
			$this->_output();
		} catch (Exception $e) {
			system_db::getAdapter()->rollBack();
			$this->_error($e->getMessage());
		}
	}
	
	private function _checkType() {
		$type = trim($this->_post('type'));
		$typeConcept = new resource_file_type();
		if(!$typeConcept->has($type)) {
			$this->_error('Invalid Params: invalid file type.');
		}
		if(!isset($_FILES["file"]) || !is_uploaded_file($_FILES["file"]["tmp_name"]) || $_FILES["file"]["error"] != 0) {
			$this->_error('Invalid upload.');
		}
		return $typeConcept;
	}
	
	/**
	 * 解决 SWFUpload SESSION  丢失问题
	 */
	private function _resetSession() {
		if(!($sid = trim($this->_post('sid')))) {
			$this->_error('Invalid Params.');
		}
		session_write_close();
		session_id($sid);
		session_start();
	}
}
